package xyz.ibenben.zhongdian.system.controller.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.util.FileUtil;
import xyz.ibenben.zhongdian.system.controller.BaseController;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.entity.sys.SysUserRole;
import xyz.ibenben.zhongdian.system.form.sys.SysUserForm;
import xyz.ibenben.zhongdian.system.service.impl.RedisService;
import xyz.ibenben.zhongdian.system.service.sys.SysRoleService;
import xyz.ibenben.zhongdian.system.service.sys.SysUserRoleService;
import xyz.ibenben.zhongdian.system.service.sys.SysUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * 系统用户控制类
 * 提供了一些基本的服务，如初始化、获取用户列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("sysUserForm")
@RequestMapping("/sys/sysUser")
public class SysUserController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "sysUser";

    @Resource
    private SysUserService userService;
    @Resource
    private SysUserRoleService userRoleService;
    @Resource
    private SysRoleService roleService;
    @Resource
    private RedisService redisService;

    /**
     * 初始化
     *
     * @param map         参数
     * @param sysUserForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute SysUserForm sysUserForm, HttpSession session) {
        map.addAttribute("provinceList", redisService.get("provinceList"));
        map.addAttribute("cityList", redisService.get("cityList"));
        map.addAttribute("regionList", redisService.get("regionList"));
        SysUserForm newSysUserForm = new SysUserForm();
        if (sysUserForm != null) {
            newSysUserForm = sysUserForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newSysUserForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newSysUserForm);
    }

    /**
     * 获取用户列表
     *
     * @param map         参数
     * @param sysUserForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取用户列表")
    public String getAll(Model map, @ModelAttribute SysUserForm sysUserForm) {
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), sysUserForm);
        Page<SysUser> page = PageHelper.startPage(sysUserForm.getPageIndex(), sysUserForm.getPageSize());
        List<SysUser> list = userService.findAll(sysUserForm);
        map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
        map.addAttribute(Constants.PI, page.toPageInfo());
        return "sys/" + String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除用户记录
     *
     * @param id      主键
     * @param request 请求
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除用户记录")
    public String delete(@RequestParam("id") Long id, HttpServletRequest request, SessionStatus status) {
        userService.delete(id, request);
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

    /**
     * 删除用户列表
     *
     * @param sysUserForm 条件参数
     * @param request     请求
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除用户列表")
    public String deleteAll(@ModelAttribute SysUserForm sysUserForm, HttpServletRequest request, SessionStatus status) {
        if (sysUserForm.getSelectIds() != null) {
            String[] ids = sysUserForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                userService.delete(Long.parseLong(id), request);
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

    /**
     * 打开用户添加页面
     *
     * @param map 参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开用户添加页面")
    public String openAddPage(Model map) {
        map.addAttribute(ENTITYNAME, new SysUser());
        return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存用户添加记录
     *
     * @param sysUser       实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存用户添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) SysUser sysUser,
                                 BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        SysUser user = userService.selectByUsername(sysUser.getUsername());
        if (null != user) {
            bindingResult.rejectValue("username", "misFormat", "这个用户名称已经存在了！请更改!");
            return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
        }
        if (!bindingResult.hasErrors()) {
            sysUser.setEnable(1);
            userService.save(sysUser, request);
            status.setComplete();
            return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
        } else {
            return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
        }
    }

    /**
     * 打开用户修改页面
     *
     * @param map     参数
     * @param request 请求
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开用户修改页面")
    public String openEditPage(Model map, HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute(Constants.SESSIONID);
        map.addAttribute(ENTITYNAME, userService.selectByKey(userId));
        return "sys/" + String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新用户修改记录
     *
     * @param sysUser       实体
     * @param bindingResult 校验
     * @param request       请求
     * @param file          参数
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新用户修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) SysUser sysUser, BindingResult bindingResult,
                                  HttpServletRequest request, @RequestParam("image") MultipartFile file, SessionStatus status) {
        String path = FileUtil.addPhoto(file, request);
        SysUser info = userService.selectByKey(sysUser.getId());
        if (!info.getUsername().equals(sysUser.getUsername())) {
            SysUser user = userService.selectByUsername(sysUser.getUsername());
            if (null != user) {
                bindingResult.rejectValue("username", "misFormat", "这个用户名称已经存在了！请更改!");
                return "sys/" + String.format(Constants.EDITPAGE, ENTITYNAME);
            }
        }
        if (!bindingResult.hasErrors()) {
            sysUser.setHead(path);
            userService.updateNotNull(sysUser, request);
            request.getSession().setAttribute(Constants.SESSION, sysUser);
            status.setComplete();
            return "redirect:/index";
        } else {
            return "sys/" + String.format(Constants.EDITPAGE, ENTITYNAME);
        }
    }

    /**
     * 浏览用户记录
     *
     * @param map         参数
     * @param id          主键
     * @param sysUserForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览用户记录")
    public String openViewPage(Model map, @RequestParam Long id, @ModelAttribute SysUserForm sysUserForm) {
        SysUser user = userService.findByKey(id);
        map.addAttribute(ENTITYNAME, user);
        return "sys/" + String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

    /**
     * 打开分配角色页面
     *
     * @param map 参数
     * @param id  主键
     * @return 页面
     */
    @GetMapping("/roles")
    @SystemControllerLog(description = "打开分配角色页面")
    public String openRolesPage(Model map, @RequestParam Long id) {
        map.addAttribute("userId", id);
        map.addAttribute("roleList", roleService.queryRoleListWithSelected(id));
        return "sys/sysUser/roles";
    }

    /**
     * 保存用户角色
     *
     * @param id      主键
     * @param roleIds 参数
     * @return 页面
     */
    @RequestMapping("/saveUserRoles")
    @SystemControllerLog(description = "保存分配角色记录")
    public String saveUserRoles(@RequestParam Long id, @RequestParam("roleId") String roleIds, SessionStatus status) {
        SysUserRole sur = new SysUserRole();
        sur.setUserId(id);
        sur.setRoleIds(roleIds);
        userRoleService.addUserRole(sur);
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

    /**
     * 解锁/锁定用户记录
     *
     * @param id      主键
     * @param request 请求
     * @return 页面
     */
    @RequestMapping("/enable")
    @SystemControllerLog(description = "解锁/锁定用户记录")
    public String getCityList(@RequestParam Long id, HttpServletRequest request, SessionStatus status) {
        SysUser user = userService.selectByKey(id);
        if (user != null) {
            if (user.getEnable() == 1) {
                user.setEnable(0);
            } else {
                user.setEnable(1);
            }
            userService.updateAll(user, request);
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
    }

}
